package zhai.git.test;

/**
 * @author Created by 翟凤玺
 * @package zhai.git.test
 * @project-name 项目名称
 * @description //TODO 请对该类编写一个描述
 * @create-datetime 2021/4/26 13:42
 */
public class D {
    public static void main(String[] args) throws Exception {
        System.out.println(Thread.currentThread().getName() + "：主线程开始");
        new ThreadLog().print(1);
        // 初始化宇宙
        Thread universe = new Thread(new Universe());
        new ThreadLog().print(universe);
        // 设置宇宙为守护线程
        universe.setDaemon(true);
        new ThreadLog().print(universe);
        // 设置宇宙为最高优先级
        universe.setPriority(Thread.MAX_PRIORITY);
        // 启动宇宙
        universe.start();
        new ThreadLog().print(universe);
        // 初始化一个人
        Thread people = new Thread(new People());
        new ThreadLog().print(people);
        // 设置人的优先级 4
        people.setPriority(4);
        // 启动一个人
        people.start();
        new ThreadLog().print(people);
        // 初始化一个电视
        Thread tv = new Thread(new TV());
        new ThreadLog().print(tv);
        // 设置电视优先级最低
        tv.setPriority(Thread.MIN_PRIORITY);
        new ThreadLog().print(tv);
        //　启动一个电视
        tv.start();
        new ThreadLog().print(tv);
        // 电视插队
        tv.join();
        System.out.println(Thread.currentThread().getName() + "：主线程结束");
    }
}
// 宇宙
class Universe implements Runnable {
    @Override
    public void run() {
        while (true) {
            System.out.println(Thread.currentThread().getName() + "：宇宙永恒");
        }
    }
}
//　人类
class People implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 80; i++) {
            System.out.println(Thread.currentThread().getName() + "：人活着，第" + i + "年");
        }
        System.out.println(Thread.currentThread().getName() + "：人死了");
    }
}
//　电视
class TV implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if (i%5 == 1) {
                try {
                    Thread.sleep(10);
                    System.out.println(Thread.currentThread().getName() + "：第" + i + "年，电视故障了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "：电视使用，第" + i + "年");
        }
        System.out.println(Thread.currentThread().getName() + "：电视报废");
    }
}

//　日志
interface Log {
    void print(Object obj);
}

//　线程日志
class ThreadLog implements Log {

    @Override
    public void print(Object obj) {
        if (obj instanceof Thread) {
            System.out.println( "线程名：" + ((Thread) obj).getName() +
                                "；优先级：" + ((Thread) obj).getPriority() +
                                "；线程状态：" + ((Thread) obj).getState() );
        } else {
            System.err.println("对象不是线程对象，是：" + obj.getClass());
        }
    }
}

